package com.mugui.spring.net.forward;

import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mugui.Mugui;
import com.mugui.spring.base.Module;
import com.mugui.spring.net.bean.Message;
import com.mugui.spring.net.bean.NetBag;
import com.mugui.spring.net.websocket.WebSocketManager;

import cn.hutool.core.codec.Base64;

@Component
@Module(name = "&forward", type = Module.INSERT)
public class ForwardNetBag implements Mugui {

	@Autowired
	private ForwardManager forwardManager;

	@Autowired
	private WebSocketManager webSocketManager;

	public Object New(NetBag netBag) {
		if (!webSocketManager.isOpenWebSocket()) {
			return Message.ok();
		}
		ForwardBean forwardBean = ForwardBean.newBean(ForwardBean.class, netBag.getData());
		String md5 = forwardBean.getMd5();
		forwardBean.setMd5(null);
		String string = new String(Base64.decode(md5), Charset.forName("utf-8"));

		if (!forwardBean.toString().equals(ForwardBean.newBean(ForwardBean.class, string).toString())) {
			System.out.println("解码：" + string + "原:" + forwardBean.toString());
			return Message.error("非法的注入方式，已封禁该ip对服务器的访问");
		}
		if (StringUtils.isBlank(forwardBean.getUrl())) {
			forwardBean.setUrl("http://" + netBag.getFrom_host() + ":" + netBag.getFrom_port());
		}
		System.out.println(forwardBean.getUrl() + ":" + forwardBean.toString());
		forwardManager.add(forwardBean.getUrl(), forwardBean);
		if (StringUtils.isNotBlank(forwardBean.getWs())) {
			webSocketManager.add(forwardBean.getWs(), forwardBean.getWs());
		}
		return Message.ok();
	}

	public Object delDataManager(NetBag netBag) {
		return Message.ok();
	}

	public Object addDataManager(NetBag netBag) {
		return Message.ok();
	}
}
